#include "MntFile.h"


#define DBG std::cout<<__FILE__<<":"<<__LINE__<<std::endl;

MntFile::MntFile(const char* s, const char* t)
{
    _vertices = NULL;
    _faces = NULL;
    _tex = NULL;
    load(s);
    calcTex(t);
}

void MntFile::load(const char* s)
{
    if(_vertices)
	{
	    delete [] _vertices;
	    _vertices = NULL;
	}
 
    if(_faces)
	{
	    delete [] _faces;
	    _faces = NULL;
	}
    
    std::ifstream mnt (s, std::ios::in);
    if(!mnt)
	{
	    std::cerr << "Impossible d'ouvrir le fichier " << s << std::endl;
	    exit (-1);
	}
       
    int ncols, nrows, trash, nodata;

    std::string cle;
    for(int i = 0; i < 6; i++)
	{
	    mnt >> cle;
	    if (cle == "ncols") mnt >> ncols;
	    else if (cle == "nrows") mnt >> nrows;
	    else if (cle == "NODATA_value") mnt >> nodata;
	    else if (cle == "xllcorner" || cle == "yllcorner" || cle == "cellsize")
		mnt >> trash;
	}
    _nrows = nrows;
    _ncols = ncols;
    int res = ncols*nrows;
    _vertices = new float[res*3];
    _nbVertices = res * 3;
	for(int i = 0; i < _nbVertices; i+=3)
	    {
			_vertices[i] = (i/3)/_nrows;
			_vertices[1+i] = (i/3)%_nrows;
     		mnt >> _vertices[2+i];
     		if ( _vertices[2+i] == nodata) 
				_vertices[2+i] = 100;
	    }
    mnt.close();
	calcFaces();

	}


void MntFile::calcFaces()
{
    _nbFaces = (_ncols-1)*(_nrows-1)*6;
    _faces = new GLuint[_nbFaces];
    long long int k = 0;
    for(int i = 0; i < _nrows-1; i++)
	{
	    for(int j = 0; j < _ncols-1; j++)
		{
		    _faces[k++] = _ncols*i+j;
		    _faces[k++] = _ncols*i+(j+1);
		    _faces[k++] = _ncols*(i+1)+j;
		    
		    _faces[k++] = _ncols*i+(j+1);
		    _faces[k++] = _ncols*(i+1)+(j+1);
		    _faces[k++] = _ncols*(i+1)+j;
		    
		} 
	}
}


void MntFile::calcTex(const char* t)
{
	if(_tex)
	{
		delete [] _tex;
		_tex = NULL;
	}
	
	_tex = new float[_ncols*_nrows*2];
    long long int k = 0;
    for(int i = 0; i < _nrows; i++)
    {
      for(int j = 0; j < _ncols; j++)
      {  
		_tex[k++] = (float)j/_ncols;
		_tex[k++] = 1-(float)i/_ncols;
      }
    }
    _texObj = ReadPNGFromFile(t);
    glEnable(GL_TEXTURE_2D);
    glGenTextures(1, &_texObj->id);
    glBindTexture(GL_TEXTURE_2D,_texObj->id);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexImage2D (GL_TEXTURE_2D, 
		  0, 
		  _texObj->internalFormat, 
		  _texObj->width, 
		  _texObj->height, 
		  0, 
		  _texObj->format, 
		  GL_UNSIGNED_BYTE, 
		  _texObj->texels);
}


MntFile::~MntFile()
{
	if(_faces)
	    free(_faces);
	if(_vertices)
		delete [] _vertices;
	if(_tex)
		delete [] _tex;
}

float * MntFile::getTex()
{
	return _tex;
}

GLuint MntFile::getTexID()
{
	return _texObj->id;
}

float * MntFile::getVertices()
{
    return _vertices;
}

GLuint * MntFile::getFaces()
{
    return _faces;
}

long long int MntFile::getNbVertices()
{
    return _nbVertices;
}

long long int MntFile::getNbFaces()
{
    return _nbFaces;
}

